#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Author   : long.hai
@Contact  : 1982964634@qq.com
"""
import datetime
import json

import requests


class SessionState(object):

    def __init__(self, ws):
        self.ws = ws
        self.global_pool = {}
        self.env_pool = {}
        self.case_pool = {}
        self.log_text = ''
        self.image_urls = []
        self.report_id = 0
        self.testcase_id = 0
        self.step_report_list = []
        self.extract_state = False
        self.extract_path = ''

    async def now(self):
        now_time = datetime.datetime.now()
        formatted_time = now_time.strftime(f"%Y-%m-%d %H:%M:%S.{now_time.strftime('%f')[:-3]}")  # 格式化输出
        return formatted_time

    async def log_info(self, msg, start='', end='\n'):
        msg = "%s<span style='color: #1089ff'>%s</span> - <span style='color: #328596'>INFO</span> - %s%s" % (start, await self.now(), msg, end)
        msg = msg.replace('"', "'")
        # print(msg, end='')
        if self.ws:
            msg = json.dumps({"code": 2002, "msg": msg}, ensure_ascii=False)
            await self.ws.send(msg)
            self.log_text += msg
            # await self.ws.send('{"code": 2002, "msg": "%s"}' % (msg,))
        else:
            await self.add_test_log(msg)

    async def log_error(self, msg, start='', end='\n', *args):
        print("error msg: ", msg)
        msg = "%s<span style='color: #F56C6C'>%s - ERROR - %s</span>%s" % (start, await self.now(), msg, end)
        msg = msg.replace('"', "'")
        # print(msg, end='')
        if self.ws:
            msg = json.dumps({"code": 2002, "msg": msg}, ensure_ascii=False)
            await self.ws.send(msg)
            self.log_text += msg
            # await self.ws.send('{"code": 2002, "msg": "%s"}' % (msg,))
        else:
            await self.add_test_log(msg)

    async def collect_step_report(self, name, status, use_time):
        """
        :param name: 测试步骤名称
        :param status: 测试步骤状态
        :param use_time: 测试步骤耗时
        """
        if not self.ws:
            step_report = {
                "step_name": name,
                "status": status,
                "image_urls": self.image_urls,
                "show": False,
                "use_time": use_time
            }
            self.step_report_list.append(step_report)

    async def add_test_log(self, msg):
        data = {"report_id": self.report_id, "testcase_id": self.testcase_id, "type": "ui", "log": msg}
        addr = "http://yunhai.nat300.top"
        # host = "http://192.168.1.109:8000"
        # host = "http://autotest.zaxh.cn"
        url = f'{addr}/api/report/ui/running/log'
        result = requests.post(url, json=data).json()
        assert result["status"] == 1000
